package service

import (
	"context"
	"gitee.com/jn-qq/simple-stress-testing/request"
	"math/rand"
	"net/http"
	"sync"
	"time"
)

func Dispose(ctx context.Context, wg *sync.WaitGroup, chanID, rn int, rSpaceTime time.Duration, requests ...*request.Request) {
	defer wg.Done()
	defer request.ConcurrencyMap.CNDel(1)
	n := 0
	var wgClient sync.WaitGroup
	for {
		if ctx.Err() != nil {
			break
		}
		if rn != 0 && n == rn {
			break
		} else {
			n++
		}
		// 请求
		wgClient.Add(1)
		request.ConcurrencyMap.TNAdd(1)
		go client(&wgClient, chanID, requests...)

		// 随机延时
		if rSpaceTime == 0 {
			rand.New(rand.NewSource(time.Now().UnixNano()))
			rSpaceTime = time.Duration(rand.Intn(10)) * time.Millisecond
		}
		time.Sleep(rSpaceTime)

	}
	// 等待所有的数据都发送完成
	wgClient.Wait()
}

func client(wg *sync.WaitGroup, chanId int, requests ...*request.Request) {
	defer wg.Done()
	defer request.ConcurrencyMap.TNDel(1)
	var cookies []*http.Cookie
	for _, req := range requests {
		if cookies != nil {
			req.Cookies = cookies
		}
		response := &request.Response{}
		// 根据请求类型分发请求
		switch req.Scheme {
		case request.HTTP, request.HTTPS:
			response = request.HttpClient(req)
			cookies = response.Cookies
		default:
			panic("不支持的链接类型：" + req.Scheme)
		}
		response.ChanID = chanId
		request.CH <- response
	}
}
